package com.hm.service.utils.spark;

import com.alibaba.fastjson2.JSON;
import com.hm.service.pojo.request.BigModelRequest;
import okhttp3.HttpUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 地址与鉴权信息  https://spark-api.xf-yun.com/v1.1/chat   1.5地址  domain参数为general
 * 地址与鉴权信息  https://spark-api.xf-yun.com/v2.1/chat   2.0地址  domain参数为generalv2
 * 地址与鉴权信息  https://spark-api.xf-yun.com/v3.1/chat   3.0地址  domain参数为generalv2
 */
public class BigModelUtils {
    private static final Logger logger = LoggerFactory.getLogger(BigModelUtils.class);

    //星火大模型3.0
//    private static final String hostUrl = "https://spark-api.xf-yun.com/v3.1/chat";
//    private static final String domain = "generalv2";
    //星火大模型1.0
    private static final String hostUrl = "https://spark-api.xf-yun.com/v1.1/chat";
    private static final String domain = "general";

    private static final String appid = "228a3069";
    private static final String apiSecret = "ODhmZTQ5M2ZkNTg2NmY0MDJiMTlmZTZj";
    private static final String apiKey = "a912b362236d32b59496e8f21e8d252c";


    //获取鉴权Url方法
    public static String getAuthUrl() {
        try {
            URL url = new URL(hostUrl);
            //时间
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = format.format(new Date());
            // 拼接
            String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "GET " + url.getPath() + " HTTP/1.1";
            // SHA256加密
            Mac mac = Mac.getInstance("hmacsha256");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
            mac.init(spec);
            byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
            // Base64加密
            String sha = Base64.getEncoder().encodeToString(hexDigits);
            // 拼接
            String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
            // 拼接地址
            HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                    addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                    addQueryParameter("date", date).//
                    addQueryParameter("host", url.getHost()).//
                    build();
            return httpUrl.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return "";
        }
    }

    public static String requestGenerator(String problem) {
        BigModelRequest request = new BigModelRequest();

        //请求头部分
        BigModelRequest.Header header = new BigModelRequest.Header();
        header.app_id = appid;
        header.uid = UUID.randomUUID().toString().substring(0, 10);
        //赋值
        request.header = header;

        //参数部分
        BigModelRequest.Parameter parameter = new BigModelRequest.Parameter();
        BigModelRequest.Parameter.Chat chat = new BigModelRequest.Parameter.Chat();
        chat.domain = domain;
        chat.temperature = 0.5;
        chat.max_tokens = 1024;
        //赋值
        parameter.chat = chat;
        request.parameter = parameter;

        //载体部分
        BigModelRequest.Payload payload = new BigModelRequest.Payload();
        BigModelRequest.Payload.Message message = new BigModelRequest.Payload.Message();
        List<BigModelRequest.Payload.Message.Text> textList = new ArrayList<>();
        BigModelRequest.Payload.Message.Text text = new BigModelRequest.Payload.Message.Text();
        text.role = "user";
        text.content = problem;
        //赋值
        textList.add(text);
        message.text = textList;
        payload.message = message;
        request.payload = payload;

        return JSON.toJSONString(request);
    }
}
